package com.ezlcp.user.task;

import com.alibaba.fastjson2.JSON;
import com.ezlcp.commons.model.SysUser;
import com.ezlcp.commons.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Elwin ZHANG
 * @description: 定时刷新Redis中的在线用户列表<br />
 * @date 2023/2/7 9:35
 */
@Component
@Slf4j
public class RefreshOnlineUserTask {
    /**
     * 是否计算在线用户
     */
    @Value("${ezlcp.online-user.calculate:false}")
    private boolean calculate;

    /***
     * @description 把token按用公司分组，即为某公司的在线用户
     * @param removeUserId 要删除的在线用户ID；如不需要删除，可以传空字符
     * @author Elwin ZHANG
     * @date 2023/2/7 16:36
     */
    public static void groupTokenByTenantId(String removeUserId) {
        var redisOp = TokenUtil.getRedisRepository();
        Map<String, Object> map = redisOp.getKeysValues("token");
        if (map == null) {
            return;
        }
        HashMap<String, List<String>> resultMap = new HashMap<>();
        //遍历所有的token,按公司ID汇总
        for (var entry : map.entrySet()) {
            String token = TokenUtil.getTokenWithNoPrefix(entry.getKey());
            SysUser user = JSON.parseObject(entry.getValue().toString(), SysUser.class);
            //删除指定用户的token
            if(user.getUserId().equals(removeUserId)){
                String message=TokenUtil.genForceOfflineMessage("You have been forced offline!");
                TokenUtil.forcedOffline(token, message);
                TokenUtil.removeToken(token);
                continue;
            }
            String tenantId = TokenUtil.dealTenantId(user.getTenantId());
            var list = resultMap.get(tenantId);
            if (list == null) {
                list = new ArrayList<>();
                resultMap.put(tenantId, list);
            }
            list.add(token);
        }

        //将汇总的结果缓存起来
        redisOp.deleteByKeyPatten(TokenUtil.ONLINE_USER_KEY);
        for (var entry : resultMap.entrySet()) {
            String key = entry.getKey();
            var list = entry.getValue();
            String value = String.join(",", list);
            TokenUtil.setOnlineUsers(key, value);
        }
    }

    @Scheduled(fixedRate = TokenUtil.TOKEN_REFRESH_MINUTES * 60 * 1000, initialDelay = 300000)
    @Scheduled(fixedRate = 60 * 1000, initialDelay = 60000)
    public void refreshOnlineUserTask() {
        if (!calculate) {
            return;
        }
        log.info("=============定时刷新在线用户 开始===========");
        groupTokenByTenantId("");
        log.info("=============定时刷新在线用户 结束===========");
    }
}
